package com.example.administrator.wallet.view.activity.asset;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.acker.simplezxing.activity.CaptureActivity;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.wallet.R;
import com.example.administrator.wallet.base.BaseActivity;
import com.example.administrator.wallet.constant.Api;
import com.example.administrator.wallet.intf.IRequestCallback;
import com.example.administrator.wallet.intf.IRequestManager;
import com.example.administrator.wallet.model.bean.BTCParameterBean;
import com.example.administrator.wallet.model.bean.InfoUpdateBean;
import com.example.administrator.wallet.model.bean.MainBean;
import com.example.administrator.wallet.model.bean.ParameterBean;
import com.example.administrator.wallet.utils.AESUtils;
import com.example.administrator.wallet.utils.DecimalUtil;
import com.example.administrator.wallet.utils.DimbgUtils;
import com.example.administrator.wallet.utils.ListDataSave;
import com.example.administrator.wallet.utils.RequestFactory;
import com.example.administrator.wallet.utils.SharedPrefsUtil;
import com.example.administrator.wallet.view.activity.mine.Contacts.HasContactActivity;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.Transaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ExtendedKey;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip32.ValidationException;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip39.SeedCalculator;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.AddressIndex;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.BIP44;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bip44.CoinPairDerive;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BTCTransaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BitCoinECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.bitcoin.BitcoinException;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.CallTransaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.EthECKeyPair;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.ethereum.EthTransaction;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.Base58;
import com.example.mylibrary.src.main.java.com.quincysx.crypto.utils.HexUtils;
import com.google.gson.Gson;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

import static com.example.mylibrary.src.main.java.com.quincysx.crypto.CoinTypes.BitcoinTest;

public class AccountActivity extends BaseActivity {

    @Bind(R.id.finish_img)
    ImageButton finishImg;
    @Bind(R.id.view_title)
    TextView viewTitle;
    @Bind(R.id.linear_saoyisao)
    LinearLayout linearSaoyisao;
    @Bind(R.id.title_yue)
    TextView title_yue;
    @Bind(R.id.title_icon)
    ImageView titleIcon;
    @Bind(R.id.title_count)
    TextView titleCount;
    @Bind(R.id.confirm)
    Button confirm;
    @Bind(R.id.linear)
    LinearLayout mLinear;
    @Bind(R.id.relative)
    RelativeLayout mRelative;
    @Bind(R.id.address)
    EditText address;
    @Bind(R.id.counts)
    EditText counts;
    @Bind(R.id.editText)
    EditText editText;
    @Bind(R.id.price)
    TextView price;
    @Bind(R.id.lianxiren)
    LinearLayout lianxiren;
    @Bind(R.id.mSeekBar)
    SeekBar mSeekBar;
    @Bind(R.id.price_size)
    TextView priceSize;
    @Bind(R.id.danwei)
    TextView danwei;
    private View view;
    private Button submit;
    private EditText ed1;
    private EditText ed2;
    private EditText ed3;
    private EditText ed4;
    private EditText ed5;
    private EditText ed6;
    private List<EditText> ed_list = new ArrayList<>();
    private ImageView hidePopup;
    private static InputMethodManager imm;
    private static final int REQ_CODE_PERMISSION = 0x1111;
    private MainBean.DataBean.ListBean addr;
    private String token;
    private String mAddr;
    private String mCounts;
    private String beizhu;
    private String raw;
    private IRequestManager reqequestManager;
    private SharedPreferences wallet;
    private TextView coin_count;
    private TextView transactionCoin;
    private BTCParameterBean bean;
    private PopupWindow window;
    private BitCoinECKeyPair parse;
    private String Raw;
    private List<Double> unspend;
    private long realOut;
    private BTCTransaction.Input[] inputs;

    @Override
    public void init() {
        confirm.setOnClickListener(null);
        unspend = new ArrayList<>();
        wallet = getSharedPreferences("wallet", MODE_PRIVATE);
        setStatuColor();
        finishImg.setVisibility(View.VISIBLE);
        viewTitle.setVisibility(View.GONE);
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        token = intent.getStringExtra("token");
        addr = (MainBean.DataBean.ListBean) intent.getSerializableExtra("addr");
        String string = getResources().getString(R.string.address);
        address.setHint(addr.getCoin_symbol() + string);
        titleCount.setText(addr.getBalance());
        title_yue.setText(R.string.yue);
        initRequest();
    }

    private void initRequest() {
        reqequestManager = RequestFactory.getReqequestManager();
        String coin_symbol = addr.getCoin_symbol();
        if (coin_symbol.equals("BTC")) {
            titleIcon.setSelected(true);
            counts.setSelected(true);
            String addrs = addr.getAddr();
            danwei.setText(" btc");
            reqequestManager.httpPost(Api.BaseUrl + Api.BTCParameter, Api.getBTCParameter(token, addr.getCoin_symbol(), addrs), new IRequestCallback() {
                @Override
                public void onSuccess(String Response) {
                    Gson mGson = new Gson();
                    bean = mGson.fromJson(Response, BTCParameterBean.class);
                    if (bean.getCode() == 200) {
                        danwei.setText(" " + bean.getData().getCoin_unit());
                        BTCseekbar(bean);
                        BTCmPriceChange(bean);
                        BTCChangeLister(bean);
                        BTCsendTransaction(bean);
                    }
                    Log.e("TAG", bean.toString());
                }

                @Override
                public void onFailure(String error) {
                    Log.e("TAG", error);
                }
            });
        } else {
            titleIcon.setSelected(false);
            counts.setSelected(false);
            reqequestManager.httpPost(Api.BaseUrl + Api.ETHParameter, Api.getParameter(token, addr.getCoin_symbol(), addr.getAddr(), ""), new IRequestCallback() {
                private ParameterBean parameterBean;

                @Override
                public void onSuccess(String Response) {
                    Gson mGson = new Gson();
                    parameterBean = mGson.fromJson(Response, ParameterBean.class);
                    if (parameterBean.getCode() == 200) {
                        danwei.setText(" " + parameterBean.getData().getCoin_unit());
                        seekbar(parameterBean);
                        mPriceChange(parameterBean);
                        ChangeLister(parameterBean);
                        sendTransaction(parameterBean);
                    }
                }

                @Override
                public void onFailure(String error) {
                    Log.e("TAG", error);
                }
            });
        }
    }

    private void BTCsendTransaction(final BTCParameterBean bean) {
        mAddr = address.getText().toString().trim();
        mCounts = counts.getText().toString().trim();
        beizhu = editText.getText().toString().trim();
        if (mAddr != null && !(mAddr.equals("")) && mCounts != null && !(mCounts.equals(""))) {
            confirm.setSelected(true);
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    BTCShouPopup(bean);
                }
            });
        } else {
            confirm.setSelected(false);
            confirm.setOnClickListener(null);
        }
    }

    private void BTCShouPopup(final BTCParameterBean bean) {
        loadPopupView(bean.getData().getCoin_symbol());
        window.showAsDropDown(mRelative, 0, 0);
        popupInputMethodWindow();
        DimbgUtils.dimBackground(AccountActivity.this, 0.5f);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                DimbgUtils.dimBackground(AccountActivity.this, 1.0f);
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String log = wallet.getString("log", "");
                String s = ed1.getText().toString();
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                window.dismiss();
                if (ed6.isSelected() && log.equals(Base58.encode(s.getBytes()))) {
                    try {
                        //获取BTCKeyPair
                        ListDataSave wallet = new ListDataSave(AccountActivity.this, "wallet");
                        List<String> zhujici = wallet.getDataList("zhujici");

                        byte[] seed = new SeedCalculator().calculateSeed(zhujici, "");
                        try {
                            ExtendedKey extendedKey = ExtendedKey.create(seed);
                            AddressIndex index_Bitcoin = BIP44.m().purpose44()
                                    .coinType(BitcoinTest)
                                    .account(0)
                                    .external()
                                    .address(0);
                            CoinPairDerive pairDerive = new CoinPairDerive(extendedKey);
                            parse = (BitCoinECKeyPair) pairDerive.derive(index_Bitcoin);
                        } catch (ValidationException e) {
                            e.printStackTrace();
                        }

                        //生成BTC交易
                        //这里根据后台返回的未花费条目 自己挑选出最合适的条目作为此次转账非花费
                        if (bean.getData().getUnspent() == null) {
                            Toast.makeText(AccountActivity.this, R.string.transcation_error, Toast.LENGTH_SHORT).show();
                        } else {
                            Double total = 0.0;//该次交易总输入

                            double fee = Double.valueOf(priceSize.getText().toString());//矿工费 通过滑动条获得
                            double out = Double.valueOf(counts.getText().toString());//转出币

                            double all_coin = fee + out;

                            unspend.clear();
                            int unsp_size = bean.getData().getUnspent().size();
                            Double[] unsp = new Double[unsp_size];

                            for (int i = 0; i < bean.getData().getUnspent().size(); i++) {
                                unsp[i] = Double.valueOf(bean.getData().getUnspent().get(i).getValue_dec());
                            }

                            Arrays.sort(unsp);

                            for (int i = 0; i < unsp.length; i++) {
                                total += unsp[i];
                                unspend.add(unsp[i]);
                                if (total > all_coin) {
                                    break;
                                }
                            }

                            String myAddr = parse.getAddress();
                            inputs = new BTCTransaction.Input[unspend.size()];
                            for (int i = 0; i < unspend.size(); i++) {
                                Double myUnsp = unspend.get(i);
                                for (int j = 0; j < bean.getData().getUnspent().size(); j++) {
                                    BTCParameterBean.DataBean.UnspentBean unspentBean = bean.getData().getUnspent().get(j);
                                    Double unsp_valueDec = Double.valueOf(unspentBean.getValue_dec());
                                    if (myUnsp.equals(unsp_valueDec)) {
                                        BTCTransaction.OutPoint outPoint = new BTCTransaction.OutPoint(HexUtils.fromHex(unspentBean.getTxid()), Integer.parseInt(unspentBean.getTx_output_n()));
                                        inputs[i] = new BTCTransaction.Input(outPoint, BTCTransaction.Script.buildOutput(myAddr), 0xffffffff);
                                    }
                                }
                            }

                            //String txid = "7b5a888f7c956531aa3022aaef12f09ae4b1ef554849d324bfe1193c6cd1e754";
                            //BTCTransaction.OutPoint outPoint = new BTCTransaction.OutPoint(HexUtils.fromHex(txid), 0);

                            BTCTransaction.Output[] outputs = new BTCTransaction.Output[2];

                            //double out = Double.parseDouble(counts.getText().toString().trim());
                            realOut = (long) (out * 1e8);

                            double zhaoling = total - out - fee;
                            long realZhaoling = (long) (zhaoling * 1e8);

                            BTCTransaction.Output output1 = new BTCTransaction.Output(realOut, BTCTransaction.Script.buildOutput(address.getText().toString().trim()));
                            outputs[0] = output1;//收款 1
                            BTCTransaction.Output output2 = new BTCTransaction.Output(realZhaoling, BTCTransaction.Script.buildOutput(parse.getAddress()));
                            outputs[1] = output2;//找零
                            BTCTransaction transaction = new BTCTransaction(inputs, outputs, 0);
                            byte[] sign = transaction.sign(parse);
                            Raw = HexUtils.toHex(sign);
                            Log.e("TAG", Raw);
                            SendBTCTranscation(bean);
                        }
                    } catch (BitcoinException e) {
                        e.printStackTrace();
                    } catch (ValidationException e) {
                        e.printStackTrace();
                    }
                } else {
                    Toast.makeText(AccountActivity.this, R.string.psw_error, Toast.LENGTH_SHORT).show();
                    loadPopupView(bean.getData().getCoin_symbol());
                }
            }
        });

        hidePopup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                window.dismiss();
            }
        });
    }

    private void SendBTCTranscation(BTCParameterBean bean) {
        BTCParameterBean.DataBean data = bean.getData();
        String coin_symbol = data.getCoin_symbol();
        String mAddrs = parse.getAddress();
        String tAddr = address.getText().toString();
        String input = inputs.toString();
        String value = counts.getText().toString();
        String iFee = priceSize.getText().toString();
        reqequestManager.httpPost(Api.BaseUrl + Api.BTCTransaction, Api.getBTCTranscation(token, coin_symbol, mAddrs, tAddr, input, value, iFee, "", Raw), new IRequestCallback() {
            @Override
            public void onSuccess(String Response) {
                Gson mGson=new Gson();
                InfoUpdateBean fromJson = mGson.fromJson(Response, InfoUpdateBean.class);
                Toast.makeText(AccountActivity.this, fromJson.getMessage(), Toast.LENGTH_SHORT).show();
                Intent intent=new Intent();
                if(fromJson.getCode()==200){
                    AccountActivity.this.setResult(200,intent);
                    finish();
                }
            }

            @Override
            public void onFailure(String error) {
                Toast.makeText(AccountActivity.this, R.string.transcation_error, Toast.LENGTH_SHORT).show();
            }
        });


    }

    private void BTCChangeLister(final BTCParameterBean bean) {
        address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                BTCsendTransaction(bean);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        counts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                BTCsendTransaction(bean);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                BTCsendTransaction(bean);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void BTCmPriceChange(final BTCParameterBean bean) {
        counts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (i2 != 0) {
                    if (Double.valueOf(charSequence.toString()) > Double.valueOf(addr.getBalance())) {
                        Toast.makeText(AccountActivity.this, R.string.put_value, Toast.LENGTH_SHORT).show();
                        counts.setText("");
                    } else {
                        String s = DecimalUtil.multiply(charSequence.toString(), bean.getData().getExchange_rate());
                        price.setText(s);
                    }
                } else {
                    price.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void BTCseekbar(final BTCParameterBean bean) {
        int progree_rate = (int) ((Float.parseFloat(bean.getData().getHigh()) / Float.parseFloat(bean.getData().getLow())));
        mSeekBar.setMax(progree_rate);
        float rate = (Float.parseFloat(bean.getData().getCurrent())) / Float.parseFloat(bean.getData().getLow());
        mSeekBar.setProgress((int) rate);
        priceSize.setText(bean.getData().getCurrent());
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                String progress = BTCconvertProgress(i);
                if (i == 0) {
                    priceSize.setText(bean.getData().getLow());
                } else {
                    priceSize.setText(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void ChangeLister(final ParameterBean parameterBean) {
        address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                sendTransaction(parameterBean);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        counts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                sendTransaction(parameterBean);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                sendTransaction(parameterBean);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void sendTransaction(final ParameterBean parameterBean) {
        mAddr = address.getText().toString().trim();
        mCounts = AccountActivity.this.counts.getText().toString().trim();
        beizhu = editText.getText().toString().trim();
        if (mAddr != null && !(mAddr.equals("")) && mCounts != null && !(mCounts.equals(""))) {
            confirm.setSelected(true);
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ShouPopup(parameterBean);
                }
            });
        } else {
            confirm.setSelected(false);
            confirm.setOnClickListener(null);
        }
    }

    private void RequestTransaction(ParameterBean parameterBean, String gas_price) {
        long gasPrice = Long.valueOf(gas_price);
        String q = addr.getCoin_symbol();
        String w = addr.getAddr();
        String e = mAddr;
//                                0.0001
        String r = "0x" + Integer.toHexString((int) gasPrice);
        String t = parameterBean.getData().getGas();
        String y = parameterBean.getData().getNonce();
        String u = "0x" + raw;
        reqequestManager.httpPost(Api.BaseUrl + Api.ETHTransaction,
                Api.getETHTransaction(token,
                        addr.getCoin_symbol(),
                        addr.getAddr(),
                        mAddr,
                        counts.getText().toString(),
                        "0x" + Integer.toHexString((int) gasPrice),
                        parameterBean.getData().getGas(),
                        parameterBean.getData().getNonce(),
                        "",
                        "0x" + raw,
                        "testnet"), new IRequestCallback() {
                    @Override
                    public void onSuccess(String Response) {
                        Gson mGson=new Gson();
                        InfoUpdateBean fromJson = mGson.fromJson(Response, InfoUpdateBean.class);
                        Toast.makeText(AccountActivity.this, fromJson.getMessage(), Toast.LENGTH_SHORT).show();
                        Intent intent=new Intent();
                        if(fromJson.getCode()==200){
                            AccountActivity.this.setResult(200,intent);
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(String error) {
                        Toast.makeText(AccountActivity.this, R.string.transcation_error, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    //价值的监听改变
    private void mPriceChange(final ParameterBean parameterBean) {
        counts.addTextChangedListener(new TextWatcher() {
                                          @Override
                                          public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                                          }

                                          @Override
                                          public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                                              if (i2 != 0) {
                                                  if (Double.valueOf(charSequence.toString()) > Double.valueOf(addr.getBalance())) {
                                                      Toast.makeText(AccountActivity.this, R.string.put_value, Toast.LENGTH_SHORT).show();
                                                      counts.setText("");
                                                  } else {
                                                      String s = DecimalUtil.multiply(charSequence.toString(), parameterBean.getData().getExchange_rate());
                                                      price.setText(s);
                                                  }
                                              } else {
                                                  price.setText("");
                                              }
                                          }

                                          @Override
                                          public void afterTextChanged(Editable editable) {

                                          }
                                      }

        );
    }

    //seekBar监听改变数值

    private void seekbar(final ParameterBean parameterBean) {
        int progree_rate = (int) ((Float.parseFloat(parameterBean.getData().getHigh()) / Float.parseFloat(parameterBean.getData().getLow())));
        mSeekBar.setMax(progree_rate);
        float rate = (Float.parseFloat(parameterBean.getData().getCurrent())) / Float.parseFloat(parameterBean.getData().getLow());
        mSeekBar.setProgress((int) rate);
        priceSize.setText(parameterBean.getData().getCurrent());
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                String progress = convertProgress(i);
                if (i == 0) {
                    priceSize.setText(parameterBean.getData().getLow());
                } else {
                    priceSize.setText(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    //计算seekbar对应数值
    private String convertProgress(int intVal) {
        String multiply = DecimalUtil.multiply("21", "" + intVal);
        String divide = DecimalUtil.divide(multiply, 100000000 + "");
        return divide;
    }

    //计算BTCseekbar对应数值
    private String BTCconvertProgress(int intVal) {
        String multiply = DecimalUtil.multiply("1", "" + intVal);
        String divide = DecimalUtil.divide(multiply, 100000 + "");
        return divide;
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_account;
    }

    //弹出popup
    private void ShouPopup(final ParameterBean parameterBean) {
        loadPopupView(parameterBean.getData().getCoin_symbol());
        window.showAsDropDown(mRelative, 0, 0);
        popupInputMethodWindow();
        DimbgUtils.dimBackground(AccountActivity.this, 0.5f);
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                DimbgUtils.dimBackground(AccountActivity.this, 1.0f);
                KeyboardUtils.hideSoftInput(AccountActivity.this);
            }
        });

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String log = wallet.getString("log", "");
                String s = ed1.getText().toString();
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                window.dismiss();
                if (ed6.isSelected() && log.equals(Base58.encode(s.getBytes()))) {
                    Double coinCounts = Double.valueOf(counts.getText().toString());
                    double pow = 1 * Math.pow(10.0D, 18.0D);
                    String amount = String.valueOf((long) ((coinCounts) * pow));
                    String gasLimit = String.valueOf(Integer.valueOf(parameterBean.getData().getGas().substring(2), 16));
                    Double mPrice = Double.valueOf(priceSize.getText().toString());
                    Double mGas = Double.valueOf(gasLimit);
                    String gas_price = String.valueOf((long) (mPrice / mGas * pow));
                    String nonce = String.valueOf(Integer.valueOf(parameterBean.getData().getNonce().substring(2), 16));
                    String toAddr = mAddr.substring(2);
                     byte[] rawHash;

                    String eth_privateKey = SharedPrefsUtil.getValue(AccountActivity.this, "wallet", "eth_private", "eth");
                    String secretKey = SharedPrefsUtil.getValue(AccountActivity.this, "wallet", "secretKey", "secretKey");
                    String password = SharedPrefsUtil.getValue(AccountActivity.this, "wallet", "log", null);
                    byte[] decode = Base58.decode(password);
                    String eth_key = AESUtils.decrypt(eth_privateKey, secretKey);
//                    String eth_key = Base64.decode(eth_privateKey);
                    EthECKeyPair ecKeyPair = new EthECKeyPair(new BigInteger(eth_key, 16));
                    String address = ecKeyPair.getAddress();

                    //如果是eth
                    if(parameterBean.getData().getCoin_symbol().equals("ETH")){
                        EthTransaction ethTransaction
                                = EthTransaction.create(toAddr,
                                new BigInteger(amount),
                                new BigInteger(nonce),
                                new BigInteger(gas_price),
                                new BigInteger(gasLimit),
                                3);


                        Log.e("TAG", address);
                        try {
                            ethTransaction.sign(ecKeyPair);
                        } catch (ValidationException e) {
                            e.printStackTrace();
                        }
                        rawHash = ethTransaction.getEncoded();
                    }else{
                        //如果是toke  代币
                        if(StringUtils.isEmpty(addr.getRam_token_addr())){
                            String data_error = getResources().getString(R.string.loadData_error);
                            ToastUtils.showShort(data_error);
                            return;
                        }
                        String token_addr=addr.getRam_token_addr().substring(2);


                        CallTransaction.Function function = CallTransaction.Function.fromSignature("transfer", "address","uint256");
                        Transaction txConst = CallTransaction.createCallTransaction(
                                new BigInteger(nonce),
                                new BigInteger(gas_price),
                                new BigInteger(gasLimit),
                                token_addr,
                                new BigInteger("0"),
                                function,
                                toAddr,
                                new BigInteger(amount)
                                );
                        try {
                            txConst.sign(ecKeyPair);
                        } catch (ValidationException e) {
                            e.printStackTrace();
                        }
                        //rawHash = txConst.getData()
                        rawHash = txConst.getSignBytes();
                    }

                    raw = HexUtils.toHex(rawHash);
                    Log.e("TAG", raw);
                    RequestTransaction(parameterBean, gas_price);
                } else {
                    Toast.makeText(AccountActivity.this, R.string.pst_error, Toast.LENGTH_SHORT).show();
                    ShouPopup(parameterBean);
                }
            }
        });

        hidePopup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                window.dismiss();
            }
        });
    }

    private void loadPopupView(String name) {
        view = View.inflate(this, R.layout.popup_pay, null);
        submit = (Button) view.findViewById(R.id.submit);
        ed1 = (EditText) view.findViewById(R.id.ed1);
        ed2 = (EditText) view.findViewById(R.id.ed2);
        coin_count = (TextView) view.findViewById(R.id.coin_count);
        transactionCoin = (TextView) view.findViewById(R.id.transaction_coin);
        ed3 = (EditText) view.findViewById(R.id.ed3);
        ed4 = (EditText) view.findViewById(R.id.ed4);
        ed5 = (EditText) view.findViewById(R.id.ed5);
        ed6 = (EditText) view.findViewById(R.id.ed6);
        ed1 = (EditText) view.findViewById(R.id.ed1);
        hidePopup = (ImageView) view.findViewById(R.id.hide_popup);
        ed2.clearFocus();
        ed2.setInputType(InputType.TYPE_NULL);
        ed3.clearFocus();
        ed3.setInputType(InputType.TYPE_NULL);
        ed4.clearFocus();
        ed4.setInputType(InputType.TYPE_NULL);
        ed5.clearFocus();
        ed5.setInputType(InputType.TYPE_NULL);
        ed6.clearFocus();
        ed6.setInputType(InputType.TYPE_NULL);
        coin_count.setText(counts.getText().toString());
        String string = getResources().getString(R.string.accounts);
        transactionCoin.setText(string + name);
        final View finalView = view;
        window = new PopupWindow(finalView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        window.setFocusable(true);
        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    private void popupInputMethodWindow() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                showSoftInputFromWindow(AccountActivity.this);
                ed1.setImeOptions(EditorInfo.IME_ACTION_SEND);
                setEdStatu(ed1);
                initListEd();
            }
        });
    }

    private void initListEd() {
        ed_list.clear();
        ed_list.add(ed1);
        ed_list.add(ed2);
        ed_list.add(ed3);
        ed_list.add(ed4);
        ed_list.add(ed5);
        ed_list.add(ed6);
    }

    private void setEdStatu(final EditText ed) {
        ed.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                if ((ed1.getText().toString().trim()).equals("") || ed1.getText().toString() == null) {
                    initListEd();
                    hideSelected(ed_list);
                } else {
                    switch (ed1.getText().length()) {

                        case 1:
                            initListEd();
                            ed_list.remove(ed1);
                            hideSelected(ed_list);
                            ed1.setSelected(true);
                            break;
                        case 2:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            hideSelected(ed_list);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 3:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            hideSelected(ed_list);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 4:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            ed_list.remove(ed4);
                            hideSelected(ed_list);
                            ed4.setSelected(true);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 5:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            ed_list.remove(ed4);
                            ed_list.remove(ed5);
                            hideSelected(ed_list);
                            ed5.setSelected(true);
                            ed4.setSelected(true);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                        case 6:
                            initListEd();
                            ed_list.remove(ed1);
                            ed_list.remove(ed2);
                            ed_list.remove(ed3);
                            ed_list.remove(ed4);
                            ed_list.remove(ed5);
                            ed_list.remove(ed6);
                            hideSelected(ed_list);
                            ed6.setSelected(true);
                            ed5.setSelected(true);
                            ed4.setSelected(true);
                            ed3.setSelected(true);
                            ed2.setSelected(true);
                            ed1.setSelected(true);
                            break;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    public void hideSelected(List<EditText> list_ed) {
        for (int i = 0; i < list_ed.size(); i++) {
            list_ed.get(i).setSelected(false);
        }
    }

    public void showSoftInputFromWindow(Activity activity) {
        ed1.setFocusable(true);
        ed1.setFocusableInTouchMode(true);
        ed1.requestFocus();
        imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(ed1, 0);
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    @OnClick({R.id.finish_img, R.id.linear_saoyisao, R.id.confirm, R.id.lianxiren})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.finish_img:
                finish();
                break;
            case R.id.linear_saoyisao:
                if (ContextCompat.checkSelfPermission(AccountActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(AccountActivity.this, new String[]{Manifest.permission.CAMERA}, REQ_CODE_PERMISSION);
                } else {
                    startCaptureActivityForResult();
                }
                break;
            case R.id.lianxiren:
                Intent intent = new Intent(AccountActivity.this, HasContactActivity.class);
                intent.putExtra("selected", 1);
                startActivityForResult(intent, CaptureActivity.REQ_CODE);
                break;
        }
    }


    private void startCaptureActivityForResult() {
        Intent intent = new Intent(AccountActivity.this, CaptureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putBoolean(CaptureActivity.KEY_NEED_BEEP, CaptureActivity.VALUE_BEEP);
        bundle.putBoolean(CaptureActivity.KEY_NEED_VIBRATION, CaptureActivity.VALUE_VIBRATION);
        bundle.putBoolean(CaptureActivity.KEY_NEED_EXPOSURE, CaptureActivity.VALUE_NO_EXPOSURE);
        bundle.putByte(CaptureActivity.KEY_FLASHLIGHT_MODE, CaptureActivity.VALUE_FLASHLIGHT_OFF);
        bundle.putByte(CaptureActivity.KEY_ORIENTATION_MODE, CaptureActivity.VALUE_ORIENTATION_AUTO);
        bundle.putBoolean(CaptureActivity.KEY_SCAN_AREA_FULL_SCREEN, CaptureActivity.VALUE_SCAN_AREA_FULL_SCREEN);
        bundle.putBoolean(CaptureActivity.KEY_NEED_SCAN_HINT_TEXT, CaptureActivity.VALUE_SCAN_HINT_TEXT);
        intent.putExtra(CaptureActivity.EXTRA_SETTING_BUNDLE, bundle);
        startActivityForResult(intent, CaptureActivity.REQ_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQ_CODE_PERMISSION: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startCaptureActivityForResult();
                } else {
                    Toast.makeText(this, "You must agree the camera permission request before you use the code scan function", Toast.LENGTH_LONG).show();
                }
            }
            break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                switch (resultCode) {
                    case RESULT_OK:
//                        Toast.makeText(this, data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT), Toast.LENGTH_SHORT).show();
//                        Log.e("TAG---ewm", "onActivityResult: " + data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        address.setText(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
//                            Toast.makeText(this, data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT), Toast.LENGTH_SHORT).show();
//                            Log.e("TAG---ewm", "onActivityResult: " + data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                            address.setText(data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        }
                        break;
                    case 101:
                        if (data != null) {
                            address.setText("");
                            String addr = data.getStringExtra("addr");
                            String coin_symbol = data.getStringExtra("coin_symbol");
                            String coin_symbol1 = this.addr.getCoin_symbol();
                            if(coin_symbol.equals(coin_symbol1)){
                                address.setText(addr);
                            }else{
                                Toast.makeText(this, getString(R.string.coin_error), Toast.LENGTH_SHORT).show();
                            }
                        }
                        break;
                }
                break;
        }
    }
}
